package com.admin.action.bookaction;

import com.admin.Action;
import com.admin.dao.bordao.BorDaoImpl;
import com.admin.dto.QueryReturnListBean;
import com.admin.service.bookservice.BookServiceImpl;

import com.admin.service.borservice.BorServiceImpl;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 用户续借
 */
public class BorRenewalAction extends Action {
    @Override
    public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        PrintWriter out=response.getWriter();
        HttpSession session = request.getSession();
//        System.out.println(session.getAttribute("adminInfo"));
        if(session.getAttribute("adminInfo")==null){
            out.println("<script>parent.window.location.href='error.html';</script>");
            return;
        }


        boolean bool=false;
        String renewalFree = request.getParameter("renewalFree");//续借费用
        String renewalTime = request.getParameter("renewalTime");//续借时间
        String idCard = request.getParameter("idCard");//身份证号
        String bookName=request.getParameter("shuName");
//        {renewalFree:jin_e,renewalTime:value,idCard: $("#idCard").val(),shuName:$("#shuName")}



        BookServiceImpl booksService = new BookServiceImpl();
        List<QueryReturnListBean> list=null;
        list=booksService.QueryAllBookInfoByName(idCard);

        String repayDate=null;
        for (QueryReturnListBean qrl:list) {
            if(qrl.getBookName().equals(bookName)){
                repayDate=qrl.getRepayDate();
                break;
            }
        }

        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");

        try {
            Date repayTime = ft.parse(repayDate);
            Calendar calendar  =   Calendar.getInstance();
            calendar.setTime(repayTime);
            calendar.add(calendar.DATE,Integer.valueOf(renewalTime)*7);
            Date time = calendar.getTime();
            repayDate = ft.format(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //根据用户的身份证号和所借书名增加续借的金额和续借的时间
        BorServiceImpl borService=new BorServiceImpl();
        bool=borService.getIdCardBookNameAddFreeAndTime(idCard,bookName,Double.valueOf(renewalFree),repayDate);
        if (bool){
            out.print("alert('续借成功')");
        }else {
            out.print("alert('续借失败')");
        }
    }
}
